/**
 * @file human_ai_terminal.cpp
 * @brief Implementation of human to AI terminal
 */

#include "human_ai_terminal.h"
#include <wx/utils.h>
#include <wx/tokenzr.h>

HumanAITerminal::HumanAITerminal()
{
}

HumanAITerminal::~HumanAITerminal()
{
}

bool HumanAITerminal::StartTerminal()
{
    wxPrintf("🚀 Human-AI Terminal Started\n");
    wxPrintf("Type 'help' for available commands, 'exit' to quit\n");
    return true;
}

bool HumanAITerminal::SendCommandToAI(const wxString& command, const std::map<wxString, wxString>& parameters)
{
    AIMessage message;
    message.msgType = MessageType::COMMAND_TO_AI;
    message.source = TerminalType::HUMAN_TO_AI;
    message.destination = TerminalType::AI_TO_COMPUTER;
    message.content = command;
    message.metadata = parameters;
    message.messageId = wxString::Format("human_cmd_%lld", wxGetLocalTime());
    message.contentType = ContentType::COMMAND;
    
    m_outgoingQueue.push(message);
    m_conversationHistory.push_back(message);
    
    wxPrintf("👤 Human: %s\n", command);
    return true;
}

bool HumanAITerminal::SendDataToAI(const wxString& data, ContentType contentType)
{
    AIMessage message;
    message.msgType = MessageType::DATA_REQUEST;
    message.source = TerminalType::HUMAN_TO_AI;
    message.destination = TerminalType::AI_TO_COMPUTER;
    message.content = data;
    message.messageId = wxString::Format("human_data_%lld", wxGetLocalTime());
    message.contentType = contentType;
    
    m_outgoingQueue.push(message);
    m_conversationHistory.push_back(message);
    
    wxPrintf("📊 Human sent data: %s\n", data.Left(50) + (data.length() > 50 ? "..." : ""));
    return true;
}

bool HumanAITerminal::ReceiveFromAI(AIMessage& message, int timeout_ms)
{
    if (m_incomingQueue.empty()) {
        return false;
    }
    
    message = m_incomingQueue.front();
    m_incomingQueue.pop();
    m_conversationHistory.push_back(message);
    
    DisplayAIResponse(message);
    return true;
}

bool HumanAITerminal::HasResponseFromAI()
{
    return !m_incomingQueue.empty();
}

void HumanAITerminal::StartInteractiveDialog()
{
    StartTerminal();
    ShowHelp();
    
    wxString input;
    while (true) {
        wxPrintf("\n👤 You: ");
        input.Clear();
        
        if (!wxFgets(stdin, input)) {
            break;
        }
        
        input = input.Trim();
        
        if (input.IsEmpty()) {
            continue;
        }
        
        if (input == "exit" || input == "quit") {
            wxPrintf("Goodbye! 👋\n");
            break;
        } else if (input == "help") {
            ShowHelp();
            continue;
        } else if (input == "history") {
            wxPrintf("\n📜 Conversation History:\n");
            for (const auto& msg : m_conversationHistory) {
                wxPrintf("  %s: %s\n", 
                    msg.source == TerminalType::HUMAN_TO_AI ? "You" : "AI",
                    msg.content.Left(80));
            }
            continue;
        } else if (input == "clear") {
            m_conversationHistory.clear();
            wxPrintf("History cleared.\n");
            continue;
        }
        
        // 解析并发送命令
        AIMessage message = ParseHumanInput(input);
        SendCommandToAI(message.content);
        
        // 模拟AI响应（实际中这里会连接到真正的AI）
        AIMessage response;
        response.msgType = MessageType::DATA_RESPONSE;
        response.source = TerminalType::AI_TO_HUMAN;
        response.destination = TerminalType::HUMAN_TO_AI;
        response.content = wxString::Format("I received your command: '%s'. This is a simulated response.", input);
        response.messageId = wxString::Format("ai_resp_%lld", wxGetLocalTime());
        
        m_incomingQueue.push(response);
        ReceiveFromAI(response);
    }
}

void HumanAITerminal::ExecuteBatchCommands(const std::vector<wxString>& commands)
{
    wxPrintf("🔨 Executing %zu batch commands...\n", commands.size());
    
    for (const auto& cmd : commands) {
        wxPrintf("→ %s\n", cmd);
        SendCommandToAI(cmd);
        wxMilliSleep(500); // 短暂延迟
    }
    
    wxPrintf("✅ Batch execution completed.\n");
}

AIMessage HumanAITerminal::ParseHumanInput(const wxString& input)
{
    AIMessage message;
    message.msgType = MessageType::COMMAND_TO_AI;
    message.source = TerminalType::HUMAN_TO_AI;
    message.destination = TerminalType::AI_TO_COMPUTER;
    message.messageId = wxString::Format("human_%lld", wxGetLocalTime());
    
    // 简单的命令解析
    wxString lowerInput = input.Lower();
    
    if (lowerInput.StartsWith("read ") || lowerInput.StartsWith("open ")) {
        message.contentType = ContentType::FILE_PATH;
        message.metadata["operation"] = "read";
    } else if (lowerInput.StartsWith("write ") || lowerInput.StartsWith("create ")) {
        message.contentType = ContentType::FILE_PATH;
        message.metadata["operation"] = "write";
    } else if (lowerInput.StartsWith("compile ") || lowerInput.StartsWith("build ")) {
        message.contentType = ContentType::COMMAND;
        message.metadata["operation"] = "build";
    } else if (lowerInput.StartsWith("analyze ") || lowerInput.StartsWith("check ")) {
        message.contentType = ContentType::COMMAND;
        message.metadata["operation"] = "analyze";
    } else {
        message.contentType = ContentType::TEXT;
    }
    
    message.content = input;
    return message;
}

void HumanAITerminal::DisplayAIResponse(const AIMessage& response)
{
    wxString prefix;
    switch (response.msgType) {
        case MessageType::DATA_RESPONSE:
            prefix = "🤖 AI Response";
            break;
        case MessageType::STATUS_UPDATE:
            prefix = "📊 AI Status";
            break;
        case MessageType::ERROR_MESSAGE:
            prefix = "❌ AI Error";
            break;
        case MessageType::COMPLETION_NOTICE:
            prefix = "✅ AI Complete";
            break;
        default:
            prefix = "🤖 AI";
    }
    
    wxPrintf("%s: %s\n", prefix, response.content);
}

void HumanAITerminal::ShowHelp()
{
    wxPrintf("\n📖 Available Commands:\n");
    wxPrintf("  read <file>      - Read and analyze a file\n");
    wxPrintf("  write <file>     - Write content to a file\n");
    wxPrintf("  compile <project> - Compile a project\n");
    wxPrintf("  analyze <target> - Analyze code or data\n");
    wxPrintf("  help             - Show this help\n");
    wxPrintf("  history          - Show conversation history\n");
    wxPrintf("  clear            - Clear history\n");
    wxPrintf("  exit             - Exit terminal\n");
}
